package com.hiray.wanandroid.data

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.hiray.wanandroid.net.ApiHelper
import com.hiray.wanandroid.net.response.PublicArticle
import java.lang.IllegalStateException

class PublicArticleSource(val id: String) : PagingSource<Int, PublicArticle>() {
    override fun getRefreshKey(state: PagingState<Int, PublicArticle>): Int {
        return 0
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PublicArticle> {
        val page = params.key ?: 0
        val next = page + 1
        val prev = if (page == 0) null else page - 1
        val res = ApiHelper.api().fetchPublicArticleList(id, page = params.key ?: 0)
        return if (res.isSuccess) {
            LoadResult.Page(res.items, prev, next)
        } else
            LoadResult.Error(IllegalStateException(res.errMsg))
    }
}